<!-- 2D地图组件 -->
<template>
  <div ref="mapContainer" class="h-[500px] w-full"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'

interface LayerConfig {
  data: any
  style?: L.PathOptions
}

interface Point {
  name: string
  img: string
  position: [number, number]
}

interface Props {
  center?: [number, number]
  zoom?: number
  layers?: LayerConfig[]
  points?: Point[]
}

const props = withDefaults(defineProps<Props>(), {
  center: () => [34.3645811, 107.2332184],
  zoom: 11,
  layers: () => [],
  points: () => []
})

const emit = defineEmits<{
  (e: 'ready', map: L.Map): void
  (e: 'moveend', center: [number, number]): void
}>()

const mapContainer = ref<HTMLElement>()
let map: L.Map | null = null

const initMap = () => {
  if (mapContainer.value) {
    map = L.map(mapContainer.value).setView(props.center, props.zoom)
    L.tileLayer('https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}').addTo(map)

    // 添加图层
    props.layers.forEach(layer => {
      const geoJSON = L.geoJSON(layer.data, {
        style: layer.style
      })
      geoJSON.addTo(map!)
    })

    // 添加景点标记
    props.points.forEach(point => {
      const marker = L.marker(point.position).addTo(map!)
      marker.bindPopup(`
        <div style="text-align:center;">
          <div>${point.name}</div>
          <img src="${point.img}" alt="${point.name}" style="width:200px;height:auto;margin-top:10px;" />
        </div>
      `)
    })

    // 事件监听
    map.on('moveend', () => {
      const center = map!.getCenter()
      emit('moveend', [center.lat, center.lng])
    })

    emit('ready', map)
  }
}

onMounted(() => {
  initMap()
  setTimeout(() => {
    map?.invalidateSize()
  }, 100) // 延迟一点时间，确保DOM渲染完成
})

onBeforeUnmount(() => {
  map?.remove()
  map = null
})
</script>